import { enumPaychannel } from '@/utils/enum'
import { getLocationSearch, SetStorage } from '@/utils/uni.public'


type RUNTIME = {
    develop:string // 开发 本地启动时
    release:string // 线上 打包发布，或者小程序正式运行环境
    trial?:string | undefined //体验版

    gray?:string | undefined //灰度版（仅支付宝小程序支持）
}
export class InitializeMiniProgram {

    public readonly TestHostnames:string[] = [ "https://xxx.cn","https://127.0.0.0"] // 测试环境域名

    public readonly BaseUrl:string = "" // 用于设置请求的BaseUrl
    readonly urlConfig:{ [key: string]: string } = {
        'develop,development': 'https://域名.com', //开发版
        'trial,preview': 'https://域名.com', //体验版
        'release,production': 'https://域名.com', //正式版
        "gray": 'https://域名.com' //灰度版（仅支付宝小程序支持）没有就默认取它
    }
    constructor(){
        this.BaseUrl = this.autoCheckUrl(this.getAccountInfo().runTime)
        console.log('当前运行环境请求域名=>', this.BaseUrl)
    }

    /**
     * 根据当前允许时获取请求地址
     * @param {Object} env
     */
    autoCheckUrl(env:string):string {
        const getIncludeEnv = ():string|undefined => {
            for (let key in this.urlConfig) {
                if (key.includes(env)) {
                    return this.urlConfig[key]
                }
            }
        }
        const ENV_DATA = getIncludeEnv()
        return  ENV_DATA ? ENV_DATA : this.urlConfig[env] ? this.urlConfig[env] : this.urlConfig['gray'];
    }

    /**
     * 获取小程序允许时 appid 小程序版本号，小程序允许环境如开发，体验，正式
     */
    getAccountInfo(){
        // #ifndef H5 || MP-TOUTIAO
        // @ts-ignore
        const {miniProgram:{version,appId,envVersion}} = uni.getAccountInfoSync();
        return {appId,version,runTime:envVersion}
        // #endif

        // #ifdef MP-TOUTIAO
        // @ts-ignore
        const {microapp: { mpVersion, envType,  appId },  common } = uni.getEnvInfoSync()
        return {appId,version:mpVersion,runTime:envType}
        // #endif

        // #ifdef H5
        // @ts-ignore
        const envType:string = import.meta.env.VITE_USER_NODE_ENV === 'development'?  'develop' : 'release'
        return {appId:null,version:null,runTime:envType}
        // #endif

    }

    GetH5Url = (Callback:Function) => {
        const location: Location = window.location;
        const {
            origin,
            hostname
        } = new URL(location.href)
        const isTest = /^(localhost|127\.0\.0\.1|::1|10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[0-1])\.)/.test(hostname)
        if (isTest || this.TestHostnames.includes(origin)) {
            Callback && Callback({
                develop: true,
                envType:'develop'
            })
            return  this.autoCheckUrl(this.getAccountInfo().runTime)
        } else {
            Callback && Callback({
                develop: false,
                envType:'release'
            })
            return  this.autoCheckUrl(this.getAccountInfo().runTime)
        }
    }
}



export class runtimeEnvironment {
    static isNullData: Array<null | undefined | string> = [
        null,
        'null',
        'Null',
        undefined,
        'undefined',
        'Undefined',
        '',
        ' '
    ]
    // 需要授权后是否已授权
    private isAuthorization: boolean
    //支付方式
    public paymentMethod: number | undefined
    // 标识
    public readonly userAgent: string
    // 是否是微信
    public readonly isWX: boolean
    // 是否是支付宝
    public isAliPay: boolean
    // 是否是苹果
    public readonly isiPhone: boolean
    // 是否是安卓
    public readonly isAndroid: boolean
    // PC主流浏览器
    public readonly isPC: boolean

    public readonly url: string
    // 当前环境
    public readonly devAuthDirection: string
    // 支付宝授权重定向url
    public readonly aliPayAuthRedirect_uri: string
    // 支付宝授权appid
    public readonly aliPayAuthApp_id: string
    // 支付类型
    public readonly Startup_type: number

    //微信公众号授权回调地址
    public readonly wxAuthRedirect_uri: string;

    //微信公众号appid
    public readonly weChatApp_id: string;

    constructor() {

        // 授权方向，为 'null' 为正式 根据应用 ua 匹配 其他为开发配置
        const AuthDirection: string = import.meta.env.VITE_APP_BASE_UserAuth

        this.devAuthDirection = AuthDirection

        const userAgent = window?.navigator?.userAgent

        this.userAgent = userAgent || (userAgent?.toLowerCase() as string)
        //微信客户端
        this.isWX = /MicroMessenger|microMessenger/.test(this.userAgent)
        //支付宝客服端
        this.isAliPay = ['alipay', 'Alipay'].includes(AuthDirection) || /AlipayClient|alipayClient/.test(this.userAgent)
        // 苹果
        this.isiPhone = /(iPhone|iPad|iPod|iOS)/i.test(this.userAgent)
        // 安卓
        this.isAndroid = /Android/.test(this.userAgent) || /Adr/.test(this.userAgent)

        this.isPC = /(chrome|firefox|safari)/i.test(this.userAgent)

        let urlData: string = window.location.href
        if (urlData.endsWith('#/')) {
            urlData = urlData.substring(0, urlData.length - 2)
        }

        this.url = urlData

        this.Startup_type = this.isAliPay ? enumPaychannel.aliPay : enumPaychannel.unknown


        this.aliPayAuthRedirect_uri = import.meta.env.VITE_APP_BASE_AliPayAuthRedirect_uri

        this.aliPayAuthApp_id = import.meta.env.VITE_APP_BASE_AliPayAuthApp_id

        this.wxAuthRedirect_uri = import.meta.env.VITE_APP_BASE__WXAuthRedirect_uri

        this.weChatApp_id = import.meta.env.VITE_APP_BASE_WeChatApp_id

        // 默认为没有授权
        this.isAuthorization = false
    }

    /**
     * 设置支付方式
     * @param {number} startType
     */
    set setPaymentMethod(startType: number) {
        this.paymentMethod = startType
    }

    /**
     * 设置是否授权
     * @param {boolean} auth
     */
    set setAuthorization(auth: boolean) {
        this.isAuthorization = auth
    }

    /**
     * 设置自定义设备调试
     * @param {Array<string>} UA
     */
    setUpCustomDeviceDebugging(UA:Array<string>) {

        // 指定显示调试面板设备便于调试
        const SpecifiedEquipment: Array<string> = [
                ...UA,
            '192.168.88',
            'Mozilla/5.0 (Linux; U; Android 11; zh-CN; RMX3366 Build/RKQ1.201105.002) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/69.0.3497.100 UWS/3.22.2.57 Mobile Safari/537.36 UCBS/3.22.2.57_221124174238 ChannelId(0) NebulaSDK/1.8.100112 Nebula AlipayDefined(nt:WIFI,ws:424|0|2.55,ac:sp) AliApp(AP/10.3.50.8100) AlipayClient/10.3.50.8100 Language/zh-Hans useStatusBar/true isConcaveScreen/true Region/CNAriver/1.0.0'
        ]
        for (let i = 0; i < SpecifiedEquipment.length; i++) {
            if (   this.userAgent.includes(SpecifiedEquipment[i]) ||  SpecifiedEquipment.find((ua: string) => this.url.includes(ua))
            ) {
                // 显示调试面板
                continue
            }
        }
    }

    /**
     * 动态加载Js
     * @param {string} url
     * @param {string} id
     * @param {() => {}} callback
     */

    dynamicLoadJs(url:string, id?: string, callback?: () => {}) {
        if (id && document.querySelector('#' + id)) return false
        const head:HTMLHeadElement = document.getElementsByTagName('head')[0]
        const script:HTMLScriptElement = document.createElement('script')
        script.type = 'text/javascript'
        script.src = url
        id && (script.id = id)
        if (typeof callback == 'function') {
            script.addEventListener('load', callback)
        }
        head.appendChild(script)
    }

    /**
     * 支付宝和微信公众号用户信息授权回调拿去code
     * @constructor
     */
    UserAuthorizationCallbacks(){
       const urlQuery = getLocationSearch(this.url) || {};

        if ('payOk' in urlQuery) {
            // 支付成功回调
            if (['cmbchina', 'CmbChina'].includes(this.devAuthDirection)) {
                // new VConsole()
            }
        } else {
            // 启动参数
            if ('token' in urlQuery) {
                SetStorage('Startup', {...urlQuery, paymentMethod: this.paymentMethod || this.Startup_type })
            }

            if ('auth_code' in urlQuery && 'app_id' in urlQuery) { // 支付宝授权回调参数

                this.setAuthorization = true
                SetStorage('AuthAlipay', urlQuery)
            } if ('code' in urlQuery) { // 微信授权回调参数 这里是为公众号

                this.setAuthorization = true
                SetStorage('AuthCloudFlashPay', urlQuery)
            } else {

                if (this.isAliPay || ['alipay', 'Alipay'].includes(this.devAuthDirection)) {  //支付宝
                    // 跳转到支付宝小程序 appId page页面路径 query携带到页面的参数
                    //window.location.href = 'alipays://platformapi/startapp?appId=支付宝小程序appid&page=支付宝页面路径&query=' + encodeURIComponent("qrCode=" + encodeURIComponent(this.url))
                    this.setPaymentMethod = enumPaychannel.aliPay
                    let author = `https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=${this.aliPayAuthApp_id}&scope=auth_base&redirect_uri=${this.aliPayAuthRedirect_uri}`
                    window.location.href = author
                } else if (this.isWX || ['wx', 'WX', 'WeChat', 'wechat'].includes(this.devAuthDirection)) {  //微信

                    this.setPaymentMethod = enumPaychannel.wechat
                    let author: string = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.weChatApp_id}&redirect_uri=${this.wxAuthRedirect_uri}&response_type=code&scope=snsapi_base&state=1#wechat_redirect`
                    window.location.href = author
                }
            }
        }
    }
}